package com.imelite.qyh.util;

import com.alibaba.fastjson.JSON;
import com.imelite.qyh.data.TokenBean;
import com.imelite.qyh.data.UserInfoBean;
import com.imelite.qyh.enums.WechatEnum;
import com.imelite.qyh.factory.WechatFactory;
import com.imelite.qyh.model.Wechat;

import java.util.Date;

public class WechatUtil {

    /**
     * 根据AgentId初始化Token的信息
     * @param AgentId
     * @return
     */
    public static Wechat getToken(String AgentId){
        Wechat wechat= WechatFactory.selectByPrimaryKey(AgentId);
        Date date=DateUtil.getTimeAfterByMIN(wechat.getUpdated(),110);//获取Token的110分钟之后的时间
        Date now=new Date();
        if(DateUtil.before(date,now)){//判断是否需要重新获取token
            String get_access_token_url="https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid="+wechat.getAppid()+"&corpsecret="+wechat.getAppsecre();
            String token = RequestUtil.get(get_access_token_url);
            TokenBean tokenBean=JsonUtil.toObject(token, TokenBean.class);
            wechat.setToken(tokenBean.getAccess_token());
            wechat.setUpdated(new Date());
            WechatFactory.updateByPrimaryKeySelective(wechat);
        }
        return wechat;
    }

    /**
     * 根据code获取成员信息
     * @param AgentId
     * @param code
     */
    public static UserInfoBean getWechatUserInfo(String AgentId,String code){
        Wechat wechat = getToken(AgentId);
        String str="https://qyapi.weixin.qq.com/cgi-bin/user/getuserinfo?access_token="+wechat.getToken()+"&code="+code;
        String userInfo = RequestUtil.get(str);
        System.out.println(userInfo);
        UserInfoBean userInfoBean=JSON.parseObject(userInfo,UserInfoBean.class);
        return userInfoBean;
    }
}
